﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace VirtualTournaments.Frontend.MenuControls.GenericControls
{
    using TournamentsService = Services.Tournaments.TournamentsService;
    using Tournament = Services.Tournaments.Tournament;
    using Team = Services.Tournaments.Team;
    using TeamsService = Services.Tournaments.TeamsService;
    using PlayersService = Services.Tournaments.PlayersService;
    using Player = Services.Tournaments.Player;
    using Standings = Services.Tournaments.Standings;
    using Match = Services.Tournaments.Match;
    using Journey = Services.Tournaments.Journey;

    public partial class LeagueTournamentPlayInfo : System.Web.UI.UserControl
    {
        public EventHandler GoBackButtonClicked;

        public string TournamentName
        {
            get
            {
                return TournamentNameLabel.Text;
            }
            set 
            {
                TournamentNameLabel.Text = value;
            }
        }

        protected void Page_Load() 
        {
            this.TournamentInfoControler.GoToTeamInfo += new EventHandler(GoToTeamInfo);
        }
        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (TournamentName != string.Empty)
            {
                //Get current tournament standings
                //Standings[] standings = TournamentsService.GetStandingsByTournament(TournamentName);

                Team[] teamsInTournament = TeamsService.GetTeamsByTournamentName(TournamentName);
                List<TableRow> tTable;
                TableRow row;
                TableCell cellTeam, cellMatches, cellWin, cellDraw, cellLoss, cellGS, cellGR, cellPoints;

                tTable = (List<TableRow>)Session["TournamentHardcodedTable"];
                if (tTable == null)
                {
                    int i = 0;
                    tTable = new List<TableRow>();
                    foreach (Team team in teamsInTournament)
                    {
                        row = new TableRow();

                        cellTeam = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                        cellMatches = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                        cellWin = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                        cellDraw = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                        cellLoss = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                        cellGS = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                        cellGR = new TableCell { HorizontalAlign = HorizontalAlign.Center };
                        cellPoints = new TableCell { HorizontalAlign = HorizontalAlign.Center };

                        //Button infoButton = new Button { ID = "InfoButton" + i, Text = team.Name, BackColor = System.Drawing.Color.Transparent, BorderStyle = System.Web.UI.WebControls.BorderStyle.None };
                        //infoButton.Attributes.Add("onmouseover", "this.style.cursor='hand'");
                        //infoButton.Click += new EventHandler(InfoButton_OnClick);

                        //cellTeam.Controls.Add(infoButton);
                        cellTeam.Text = team.Name;
                        cellMatches.Text = "0";
                        cellWin.Text = "0";
                        cellDraw.Text = "0";
                        cellLoss.Text = "0";
                        cellGS.Text = "0";
                        cellGR.Text = "0";
                        cellPoints.Text = "0";

                        row.Cells.Add(cellTeam);
                        row.Cells.Add(cellMatches);
                        row.Cells.Add(cellWin);
                        row.Cells.Add(cellDraw);
                        row.Cells.Add(cellLoss);
                        row.Cells.Add(cellGS);
                        row.Cells.Add(cellGR);
                        row.Cells.Add(cellPoints);

                        tTable.Add(row);
                        TournamentTable.Rows.Add(row);
                        i++;
                    }
                    Session.Add("TournamentHardcodedTable", tTable);
                }
                else
                {
                    TableRow newRow;
                    TableCell newCell;
                        //TournamentTable.Rows.RemoveAt(1);
                    //TournamentTable.Rows.RemoveAt(2);
                    //TournamentTable.Rows.RemoveAt(3);
                    //TournamentTable.Rows.RemoveAt(4);
                    foreach (TableRow tRow in tTable)
                    {
                        newRow = new TableRow();
                        for (int i = 0; i < 8; i++)
                        {
                            newCell = new TableCell();
                            newCell.HorizontalAlign = HorizontalAlign.Center;
                            newCell.Text = tRow.Cells[i].Text;
                            newRow.Cells.Add(newCell);
                        }
                        TournamentTable.Rows.Add(newRow);
                    }
                }

                //If this does not work this way, try putting journeyMatches in Session attribute
                //Match[] journeyMatches = TournamentsService.GetTournamentNextJourneyMatches(TournamentsService.GetTournamentByName(TournamentName));
                //Session.Add("CurrentJourneyMatches", journeyMatches);
                if (Session["CurrentHardcodedJourneyIndex"] == null)
                    Session.Add("CurrentHardcodedJourneyIndex", 0);
                
                int journeyIndex = (int)Session["CurrentHardcodedJourneyIndex"];

                if (Session["HardcodedJourneys"] != null)
                {
                    Journey currentJourney = ((List<Journey>)Session["HardcodedJourneys"])[journeyIndex];
                    if (Session["CurrentJourneyMatches"] == null)
                        Session.Add("CurrentJourneyMatches", currentJourney);
                    else
                        Session["CurrentJourneyMatches"] = currentJourney;
                }

                JourneyManager.FontSize = FontUnit.Medium;
            }

        }

        protected void TournamentInfoButton_OnClick(object sender, EventArgs e)
        {
            Button clickedButton = sender as Button;
            //TODO: what if null?
            this.TournamentInfoControler.TournamentName = TournamentName;
            this.TournamentInfoControler.TournamentType = "A";
            this.LeagueTournamentViewControler.ActiveViewIndex = 2;
        }

        protected void GoToTeamInfo(object sender, EventArgs e)
        {
            VirtualTournamentsFrontendEvent realEvent = e as VirtualTournamentsFrontendEvent;
            this.TeamInfoControler.TeamName = realEvent.TeamName;
            this.LeagueTournamentViewControler.ActiveViewIndex = 1;
        }

        protected void InfoButton_OnClick(object sender, EventArgs e)
        {
            Button clickedButton = sender as Button;
            //TODO: what if null?
            if (clickedButton != null)
            {
                string teamName = clickedButton.Text;

                this.TeamInfoControler.TeamName = teamName;
                this.LeagueTournamentViewControler.ActiveViewIndex = 1;
            }

        }

        protected void TournamentInformationGoBackButton_OnClick(object sender, EventArgs e)
        {
            //TODO: constants!
            this.LeagueTournamentViewControler.ActiveViewIndex = 0;
        }

        protected void TeamInfoGoBackButton_OnClick(object sender, EventArgs e)
        {
            //TODO: constants!
            this.LeagueTournamentViewControler.ActiveViewIndex = 0;
        }

        protected void TournamentInfoGoBackButton_OnClick(object sender, EventArgs e) 
        {
            GoBackButtonClicked(this, new VirtualTournamentsFrontendEvent { SenderMenu = "LeagueTournamentPlayInfo" });
        }

        protected void GetNextJourneyButton_OnClick(object sender, EventArgs e) 
        {
            //Tournament currentTournament = TournamentsService.GetTournamentByName(TournamentName);

            //Match[] journeyMatches = TournamentsService.GetTournamentNextJourneyMatches(currentTournament);
            //this.JourneyManager.SetMatches(journeyMatches);
            int currentJourneyIndex = (int) Session["CurrentHardcodedJourneyIndex"];
            currentJourneyIndex++;
            Session["CurrentHardcodedJourneyIndex"] = currentJourneyIndex;
            GetNextJourneyButton.Enabled = false;
            PlayMatchesButton.Enabled = true;
            if (Session["MatchesPlayed"] == null)
                Session.Add("MatchesPlayed", false);
            else
                Session["MatchesPlayed"] = false;
        }

        protected void PlayMatchesButton_OnClick(object sender, EventArgs e)
        {
            //Tournament currentTournament = TournamentsService.GetTournamentByName(TournamentName);

            //TournamentsService.PlayNextJourney(currentTournament);

            //Match[] journeyMatches = TournamentsService.GetTournamentLastJourneyMatches(currentTournament);

            //if (Session["CureentJourneyMatches"] == null)
            //    Session.Add("CureentJourneyMatches", journeyMatches);
            //else
            //    Session["CureentJourneyMatches"] = journeyMatches;
            Random randomResult = new Random();
            int match1LocalGoals = randomResult.Next(6);
            int match1VisitorGoals = randomResult.Next(6);
            int match2LocalGoals = randomResult.Next(6);
            int match2VisitorGoals = randomResult.Next(6);
            Journey journey = (Journey)Session["CurrentJourneyMatches"];
            Match[] JourneyMatches = journey.Matches.ToArray();
            
            JourneyMatches[0].LocalGoals = match1LocalGoals.ToString();
            JourneyMatches[0].VisitorGoals = match1VisitorGoals.ToString();

            JourneyMatches[1].LocalGoals = match2LocalGoals.ToString();
            JourneyMatches[1].VisitorGoals = match2VisitorGoals.ToString();

            Session["CurrentJourneyMatches"] = JourneyMatches;
           
            UpdateTable(JourneyMatches);
            
            if (Session["MatchesPlayed"] == null)
                Session.Add("MatchesPlayed", true);
            else
                Session["MatchesPlayed"] = true;
            PlayMatchesButton.Enabled = false;
            int currentJourneyIndex = (int) Session["CurrentHardcodedJourneyIndex"];
            if (currentJourneyIndex < 2)
                GetNextJourneyButton.Enabled = true;
            else
                TournamentNameLabel.Text += "   - TOURNAMENT FINISHED!";
        }

        private void UpdateTable(Match[] journeyMatches) 
        {
            List<TableRow> tTable = (List<TableRow>)Session["TournamentHardcodedTable"];
            
            foreach (Match match in journeyMatches) 
            {
                string localTeam = match.Local;
                int localTeamGoals = Convert.ToInt32(match.LocalGoals);
                int localTeamIndex = GetTeamIndex(localTeam);

                string visitorTeam = match.Visitor;
                int visitorTeamGoals = Convert.ToInt32(match.VisitorGoals);
                int visitorTeamIndex = GetTeamIndex(visitorTeam);
                
                tTable[localTeamIndex].Cells[1].Text = (Convert.ToInt32(tTable[localTeamIndex].Cells[1].Text) + 1).ToString();
                tTable[localTeamIndex].Cells[5].Text = (Convert.ToInt32(tTable[localTeamIndex].Cells[5].Text) + localTeamGoals).ToString();
                tTable[localTeamIndex].Cells[6].Text = (Convert.ToInt32(tTable[localTeamIndex].Cells[6].Text) + visitorTeamGoals).ToString();

                tTable[visitorTeamIndex].Cells[1].Text = (Convert.ToInt32(tTable[visitorTeamIndex].Cells[1].Text) + 1).ToString();
                tTable[visitorTeamIndex].Cells[5].Text = (Convert.ToInt32(tTable[visitorTeamIndex].Cells[5].Text) + visitorTeamGoals).ToString();
                tTable[visitorTeamIndex].Cells[6].Text = (Convert.ToInt32(tTable[visitorTeamIndex].Cells[6].Text) + localTeamGoals).ToString();

                if (localTeamGoals > visitorTeamGoals)
                {
                    tTable[localTeamIndex].Cells[2].Text = (Convert.ToInt32(tTable[localTeamIndex].Cells[2].Text) + 1).ToString();
                    tTable[localTeamIndex].Cells[7].Text = (Convert.ToInt32(tTable[localTeamIndex].Cells[7].Text) + 3).ToString();

                    tTable[visitorTeamIndex].Cells[4].Text = (Convert.ToInt32(tTable[visitorTeamIndex].Cells[4].Text) + 1).ToString();
                }
                else if (localTeamGoals < visitorTeamGoals)
                {
                    tTable[visitorTeamIndex].Cells[2].Text = (Convert.ToInt32(tTable[visitorTeamIndex].Cells[2].Text) + 1).ToString();
                    tTable[visitorTeamIndex].Cells[7].Text = (Convert.ToInt32(tTable[visitorTeamIndex].Cells[7].Text) + 3).ToString();

                    tTable[localTeamIndex].Cells[4].Text = (Convert.ToInt32(tTable[localTeamIndex].Cells[4].Text) + 1).ToString();
                }
                else 
                {
                    tTable[visitorTeamIndex].Cells[3].Text = (Convert.ToInt32(tTable[visitorTeamIndex].Cells[3].Text) + 1).ToString();
                    tTable[visitorTeamIndex].Cells[7].Text = (Convert.ToInt32(tTable[visitorTeamIndex].Cells[7].Text) + 1).ToString();

                    tTable[localTeamIndex].Cells[3].Text = (Convert.ToInt32(tTable[localTeamIndex].Cells[3].Text) + 1).ToString();
                    tTable[localTeamIndex].Cells[7].Text = (Convert.ToInt32(tTable[localTeamIndex].Cells[7].Text) + 1).ToString();
                }
            }

            tTable.Sort(new TeamComparer());

            Session["TournamentHardcodedTable"] = tTable;
        }

        private int GetTeamIndex(string teamName)
        {
            switch (teamName) 
            {
                case "Argentinos":
                    {
                        return 0;
                    }
                case "Arsenal":
                    {
                        return 1;
                    }
                case "Atlético Tucumán":
                    {
                        return 2;
                    }
                case "Banfield":
                    {
                        return 3;
                    }
                default:
                    return -1;
            }
        }

        private class TeamComparer : IComparer<TableRow>
        {
            public int Compare(TableRow team1, TableRow team2)
            {
                int team1Points = Convert.ToInt32(team1.Cells[7].Text);
                int team2Points = Convert.ToInt32(team2.Cells[7].Text);
                int team1GoalsDifference = Convert.ToInt32(team1.Cells[5].Text) - Convert.ToInt32(team1.Cells[6].Text);
                int team2GoalsDifference = Convert.ToInt32(team2.Cells[5].Text) - Convert.ToInt32(team2.Cells[6].Text);

                if (team1Points < team2Points)
                    return 1;
                else if (team1Points > team2Points)
                    return -1;
                else if (team1GoalsDifference < team2GoalsDifference)
                    return 1;
                else if (team1GoalsDifference > team2GoalsDifference)
                    return -1;
                else
                    return 0;
            }
        }
    }
}